//
//  HomeWebCell.m
//  YXFinance
//
//  Created by uplooking on 2018/10/25.
//  Copyright © 2018年 CRLong. All rights reserved.
//

#import "HomeWebCell.h"
#import <WebKit/WebKit.h>

@interface HomeWebCell()
<
UIWebViewDelegate
>
{
    UIWebView * webView;
}
@end

@implementation HomeWebCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        
        [self initView];
    }
    
    return self;
    
}
- (void)dealloc{
    
    //    [self removeWebViewObserver];
}

- (void)initView{
    
    webView = [[UIWebView alloc] init];
    [webView setDelegate:self];
    //    [webView setNavigationDelegate:self];
    webView.opaque = NO;
    webView.scrollView.scrollEnabled = NO;
    [self addSubview:webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
    }];
    
    //    [self addWebViewObserver];
    
}

////* < 方式一 >
//- (void)addWebViewObserver {
//    [webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//}
//
//- (void)removeWebViewObserver {
//    [webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
//}
//
//#pragma mark ------ < KVO > ------
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//
//
//
//    /**  < 法2 >  */
//    /**  < loading：防止滚动一直刷新，出现闪屏 >  */
//    if ([keyPath isEqualToString:@"contentSize"]) {
//        CGFloat newHeight = webView.scrollView.contentSize.height;
//
//        if (self.blockWebHeight) {
//
//            self.blockWebHeight(newHeight);
//        }
//
//        [webView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(newHeight);
//        }];
//    }
//}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // 获取webView的高度
    CGFloat newHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    
    NSLog(@"heightLeft : %f",newHeight);
    
    if (self.blockWebHeight) {
        
        self.blockWebHeight(newHeight);
    }
    
    [webView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(newHeight);
    }];
    
}



-(void)setUrl:(NSString *)url{
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [webView loadRequest:request];
}

@end
